//
//  CustomURLCache.m
//  EcmCustomer
//
//  Created by 张进 on 15/9/17.
//  Copyright (c) 2015年 张进. All rights reserved.
//

#import "CustomURLCache.h"
#import "Digest.h"
#import "Utils/APIClient.h"

@implementation CustomURLCache

static NSString * const CustomURLCacheExpirationKey = @"CustomURLCacheExpiration";
//static NSTimeInterval const CustomURLCacheExpirationInterval = 600;
static NSTimeInterval const CustomURLCacheExpirationInterval = 999999;

+ (instancetype)standardURLCache {
    static CustomURLCache *_standardURLCache = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _standardURLCache = [[CustomURLCache alloc]
                             initWithMemoryCapacity:(2 * 1024 * 1024)
                             diskCapacity:(100 * 1024 * 1024)
                             diskPath:nil];
    });
                  
    return _standardURLCache;
}
                  
#pragma mark - NSURLCache
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
//    NSCachedURLResponse *cachedResponse = [super cachedResponseForRequest:request];
    
    if (APIClient.networkStatus == AFNetworkReachabilityStatusNotReachable) {
        NSURLRequest *req = [self getCachedRequestKey:request];
        NSCachedURLResponse *cachedResponse = [super cachedResponseForRequest:req];
        
        
        if (cachedResponse) {
            NSDate* cacheDate = cachedResponse.userInfo[CustomURLCacheExpirationKey];
            NSDate* cacheExpirationDate = [cacheDate dateByAddingTimeInterval:CustomURLCacheExpirationInterval];
            if ([cacheExpirationDate compare:[NSDate date]] == NSOrderedAscending) {
                [self removeCachedResponseForRequest:request];
                return nil;
            }
        }
        
        return cachedResponse;
    }else{
        return nil;
    }
    
}

- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse
                 forRequest:(NSURLRequest *)request
{
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:cachedResponse.userInfo];
    userInfo[CustomURLCacheExpirationKey] = [NSDate date];
    
    NSCachedURLResponse *modifiedCachedResponse = [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:cachedResponse.data userInfo:userInfo storagePolicy:cachedResponse.storagePolicy];
//    NSCachedURLResponse *modifiedCachedResponse = [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:cachedResponse.data userInfo:userInfo storagePolicy:NSURLCacheStorageAllowed];
    
    
    
    NSURLRequest *req = [self getCachedRequestKey:request];
    
    [super storeCachedResponse:modifiedCachedResponse forRequest:req];
    
}

-(NSURLRequest *)getCachedRequestKey:(NSURLRequest *)request{
    
    
    NSError *error = nil;
    NSData *body = request.HTTPBody;
    NSString *str = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
    //urldecode
    NSString *result = [str stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    result = [NSString stringWithFormat:@"{%@}",result];
    result = [result stringByReplacingOccurrencesOfString:@"{encryptParam={" withString:@"{\"encryptParam\":{"];
    
    NSDictionary *apiDic = [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
    
    if (error) {
        return nil;
    }
    
    NSDictionary *dic = [apiDic objectForKey:@"encryptParam"];
    if (!dic) {
        return nil;
    }
    
    NSString *encryptKey = [dic objectForKey:@"encryptKey"];
    NSString *data = [dic objectForKey:@"data"];
    if (!encryptKey || !data) {
        return nil;
    }
    
    NSString* aesKey = [[Digest sharedInstance] rsaDecryptString:encryptKey];
    CocoaSecurityResult *text =  [CocoaSecurity aesDecryptWithBase64ESPC:data key:aesKey];
    
    if (!text.utf8String) {
        return nil;
    }
    
    NSString *params = [[NSString alloc] initWithData:text.data encoding:NSUTF8StringEncoding];
    
    
    NSString *encodeParams = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)params, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8));
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",request.URL.absoluteString,encodeParams]];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];

    return req;
}


@end